package com.lxw.multidb.modules.sql.service;

import cn.tannn.jdevelops.exception.built.BusinessException;
import com.lxw.multidb.controller.dto.DbConnectionAdd;
import com.lxw.multidb.modules.sql.dao.DbConnectionDao;
import com.lxw.multidb.modules.sql.entity.DbConnection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * DbConnectionServiceImpl
 *
 * @author lxw
 * @version V1.0
 * @date 2025/10/30 16:44
 */
@Service
@Slf4j
public class DbConnectionServiceImpl implements DbConnectionService {
    private final DbConnectionDao dbConnectionDao;

    public DbConnectionServiceImpl(DbConnectionDao dbConnectionDao) {
        this.dbConnectionDao = dbConnectionDao;
    }

    @Override
    public void add(DbConnectionAdd add) {

        boolean exists = dbConnectionDao.existsByHostAndPort(add.getHost(), add.getPort());
        if (exists) {
            throw new BusinessException("链接已存在！");
        }
        dbConnectionDao.save(add.to(DbConnection.class));
    }

    @Override
    public List<DbConnection> list() {
        return dbConnectionDao.findAll();
    }

    @Override
    public Optional<DbConnection> getById(Integer id) {
        return dbConnectionDao.findById(id);
    }


    @Override
    public void deleteById(Integer id) {
        dbConnectionDao.deleteById(id);
    }
}
